<template>
  <div class="lyric_container gradient-wrap">
    <transition name="slide-fade">
      <div
        ref="lyric_wrap"
        @click="handleLyric"
        v-show="ifShowLyric"
        class="lyric_wrap"
        :style="{backgroundImage:'url('+getSongMsg.picUrl+')'}"
        style="height: 100vh; width: 100%; overflow-y: scroll"
      >
        <div
          class="lyric_content"
          ref="lyric_content"
          :style="{ transform: 'translateY(-' + (scrollLyric - pt) + 'px)' }"
        >
          <div
            :class="{ active_lyric: activeIndex === index }"
            class="lyric_item"
            v-for="(each, index) in lyricList"
            :ref="`lyric${index}`"
            :key="index"
          >
            {{ each.lyric }}
          </div>
        </div>
      </div>
    </transition>
    <transition name="slide-fade">
      <canvas :class="backgroundImage===''?'':'opacityHide'" v-show="!ifShowLyric" id="canvas" style=""></canvas>
    </transition>
    <div
      ref="songPic"
      v-show="!ifShowLyric"
      @click="handleLyric"
      class=""
      :class="[
        $store.state.songMsg.picUrl ? 'song-pic' : '',
        ifStop ? 'stop' : 'start',
        ifShowLyric ? 'opacityHide' : 'opacityShow',
      ]"
    >
      <img ref="myimg" src="" crossOrigin="anonymous" alt="" />
    </div>
    <div class="bottom" :class="ifShowLyric ? 'opacityHide' : 'opacityPicShow'">
      <!-- 上 -->
      <div class="util-top">
        <div class="like">like</div>
        <div class="down">down</div>
        <div>change</div>
        <div @click="handleJump('Comments')">评论</div>
        <div>工具栏</div>
      </div>
      <!-- 中 -->
      <div class="util-middle">
        <DrapProgress :myAudio="myAudio"></DrapProgress>
      </div>
      <!-- 下 -->
      <div class="util-bottom">
        <div class="random">随机播放</div>
        <div class="prev" @click="handleChange(-1)">上一首</div>
        <div class="play-btn" @click="handlePlay">播放</div>
        <div class="next" @click="handleChange(1)">下一首</div>
        <div class="my-list">播放列表</div>
      </div>
    </div>
  </div>
</template>

<script>
import DrapProgress from "../../components/Drap-progress";
import { lyricSplit } from "@/utils/lyricSplit";
import { mapGetters } from "vuex";
import Grade from "grade-js";
import {getBase64} from "@/utils/base64.js"
let width = window.innerWidth,
  height = window.innerHeight;
export default {
  components: {
    DrapProgress,
  },
  mounted() {
    this.lyricList = lyricSplit(this.getSongMsg.lyric); //获取歌词
    this.myAudio = this.$store.state.audio;
    this.myAudio.addEventListener("timeupdate", (e) => {
      this.autoLyric(e);
      this.handleAutoScroll();
    });
    this.myAudio.addEventListener("ended", (e) => {
      this.activeIndex = 0;
      e.target.play();
    });
    let d1 = this.$refs.lyric_content;
    this.pt = parseInt(window.getComputedStyle(d1)["padding-top"]);
    // console.log("padding-top", this.pt);
    this.initCanvas();
    this.handleBase64();
  },
  data() {
    return {
      ifStop: false,
      baseRadius: 0,
      stepClear: 1,
      ctx: null,
      myAudio: null,
      lyricList: [],
      ifShowLyric: false,
      activeIndex: 0,
      scrollLyric: null,
      pt: 0,
      backgroundImage: "",
    };
  },
  computed: {
    ...mapGetters(["getSongMsg", "getPlayList"]),
  },
  methods: { 
    handleJump(name){
      this.$router.push({name,query:{id:this.getSongMsg.id}})
    },
   async handleBase64() {
      let _this = this;
      let picUrl = this.getSongMsg.picUrl;
      let dataUrl = await getBase64(picUrl)
      // let canvas = document.createElement("canvas");
      // // let canvas = document.getElementById('canvas')
      // canvas.width = canvas.height = this.$refs.songPic.offsetWidth;
      // let ctx = canvas.getContext("2d");
      // let image = new Image();
      // var dataUrl;
      // image.src = picUrl + "?timeStamp=" + new Date();
      // image.onload = function () {
      //   this.crossOrigin = "anonymous";
      //   ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
      //   dataUrl = canvas.toDataURL("image/png");
      //   console.log(dataUrl);
        _this.backgroundImage = dataUrl;
        // console.log(_this.$refs["myimg"]);
        _this.$refs["myimg"].src = dataUrl;
        _this.$refs["myimg"].onload = function () {
          Grade(document.querySelectorAll(".gradient-wrap")); //init
        };
      // };
    },
    autoLyric(e) {
      let currentTime = e.target.currentTime;
      try {
        let nextTime = this.lyricList[this.activeIndex + 1].time;
        // console.log(currentTime>nextTime,currentTime,nextTime)
        if (currentTime > nextTime) {
          // 拽动进度条 往右 歌词直接跳往该处
          for (var i = this.activeIndex; i < this.lyricList.length; i++) {
            // _this.activeIndex = ？
            let time = this.lyricList[i].time;
            if (currentTime < time) {
              this.activeIndex = i - 1;
              break;
            }
          }
        } else {
          //拖动进度条 往左 歌词直接跳往该处
          for (var i = this.activeIndex; i > 0; i--) {
            // _this.activeIndex = ？
            let time = this.lyricList[i].time;
            if (currentTime > time) {
              this.activeIndex = i;
              break;
            }
          }
        }
      } catch (err) {}
    },
    handleLyric() {
      this.ifShowLyric = !this.ifShowLyric;
    },
    handleAutoScroll() {
      try{
        this.scrollLyric = this.$refs["lyric" + this.activeIndex][0].offsetTop;
      }catch(err){

      }
      // console.log("translateY(-" + (this.scrollLyric - this.pt) + "px)");
      //  this.$refs['lyric_wrap'].scrollTo(0,this.$refs['lyric'+this.activeIndex][0].offsetTop);
    },
    handleChange(num) {
      let index = this.getSongMsg.recordIndex;
      let { id } = this.getPlayList[index + num];
      // console.log(index);
      this.$store
        .dispatch("PLAY_AND_SET", {
          id,
          item: this.getPlayList[index + 1],
          index: index + num,
          status: num,
        })
        .then(() => {
          //这里得是异步 在PLAY_AND_SET里面
          console.log(this.getSongMsg);
          this.lyricList = lyricSplit(this.getSongMsg.lyric); //获取歌词
          this.handleAutoScroll();
          this.handleBase64();
        });
    },
    handlePlay() {
      this.ifStop = !this.ifStop;
      this.ifStop ? this.myAudio.pause() : this.myAudio.play();
    },
    initCanvas() {
      if (!canvas || !canvas.getContext) return false;
      canvas.setAttribute("width", width);
      canvas.setAttribute("height", height);
      let ctx = canvas.getContext("2d");
      this.drawBackground(ctx);
      // this.drawPic(ctx);
    },
    drawBackground(ctx) {
      let clg = ctx.createLinearGradient(0, 0, 0, height);
      clg.addColorStop(0, "#EAE5C9"); // 第一个参数可以设定渐变位置 数字0~1之间
      clg.addColorStop(1, "#6CC6CB");
      ctx.fillStyle = clg;
      ctx.fillRect(0, 0, width, height);
    },
    drawPic(ctx) {
      let picUrl = this.$store.state.songMsg.picUrl;
      let image = new Image();
      let _this = this;
      image.src = picUrl;
      image.setAttribute("crossOrigin", "");
      image.onload = function () {
        ctx.arc(width / 2, height / 2, width / 2, 0, Math.PI * 2); //画出圆
        ctx.clip(); //裁剪上面的圆形
        // setInterval(() => {
        _this.rotatePic(ctx, this);
        // }, 1000);
      };
    },
    rotatePic(ctx, Image) {
      ctx.clearRect(0, 0, width, height);
      var xpos = width / 2;
      var ypos = height / 2;
      ctx.save();
      ctx.translate(xpos, ypos);
      ctx.rotate((this.baseRadius += (Math.PI / 180) * 2));
      ctx.translate(-xpos, -ypos);
      ctx.drawImage(Image, width / 4, height / 4, width / 2 - 10, height / 2);
      ctx.restore();
      // this.clearArc(width / 4, height / 4,width / 4,ctx);
      requestAnimationFrame(this.rotatePic.bind(this, ctx, Image));
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../assets/Play/index.less");
@import url("../../assets/public/common");
</style>